<template>
  <z-paging ref="paging" v-model="state.userList" @query="getNotifyUserList" :refresher-enabled="false">
    <!-- 通知类型 -->
    <view class="mb-3">
      <van-cell-group>
        <van-cell center use-label-slot title="通知类型" @click="state.notifyShow = true">
          <view slot="right-icon" class="flex items-center">
            <text class="mr-2">{{ state.selectType?.name }}</text>
            <image :class="state.selectType?.id === 'sos' ? ['w-10 h-7'] : ['w-9 h-7']" :src="state.selectType?.imgUrl"></image>
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <!-- 具体地址 -->
    <view class="mb-3">
      <!-- 这里如果是活动就要做切换成文本框 -->
      <van-cell-group>
        <van-cell :title="state.parentIds[0] === '' || state.parentIds.length === 4 ? '物业通知' : state.currentLocation" :border="false" use-label-slot>
          <view slot="label">
            <view v-if="state.selectType?.id === 'activity'">
              <van-field
                custom-style="border:1px solid #ddd;border-radius:16rpx"
                :value="state.content"
                type="textarea"
                placeholder="请输入留言"
                :autosize="{ maxHeight: 200, minHeight: 100 }"
                :border="false"
                @change="
                  (e: any) => {
                    state.content = e.detail;
                  }
                "
              />
            </view>
            <view v-else>
              <van-field
                custom-style="border:1px solid #ddd;border-radius:16rpx"
                :value="state.address"
                center
                clearable
                placeholder="请描述事故具体地址"
                :border="false"
                use-button-slot
                @change="
                  (e: any) => {
                    state.address = e.detail;
                  }
                "
              >
                <van-button slot="button" size="small" type="primary" @click="state.voicePopupShow = true"> 语音输入 </van-button>
              </van-field>
            </view>
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <!-- 通知方式 -->
    <view class="mb-3" v-if="isShowVerify()">
      <van-cell-group>
        <van-cell title="通知方式" :border="false" use-label-slot>
          <view slot="label">
            <view class="my-2">系统默认发送消息至呼叫器设备及小程序端</view>
            <view>
              <van-checkbox
                :value="state.notifyWay"
                shape="square"
                @change="
                  (e: any) => {
                    state.notifyWay = e.detail;
                  }
                "
              >
                电话+短信通知
              </van-checkbox>
            </view>
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <!-- 通知备注 -->
    <view class="mb-3">
      <van-cell-group>
        <van-cell title="通知备注" use-label-slot>
          <view slot="label">
            <van-field
              custom-style="border:1px solid #ddd;border-radius:16rpx"
              :value="state.remark"
              center
              clearable
              placeholder="请输入通知备注"
              :border="false"
              @change="
                (e: any) => {
                  state.remark = e.detail;
                }
              "
            >
            </van-field>
          </view>
        </van-cell>
        <van-cell center title="是否通知物业" use-label-slot v-if="isShowVerify()">
          <view slot="right-icon">
            <van-switch
              size="24px"
              :checked="state.notifyPmc"
              active-color="#ffc330"
              @change="
                (e: any) => {
                  state.notifyPmc = e.detail;
                }
              "
            />
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <!-- 通知对象 -->
    <view class="mb-3">
      <van-cell-group>
        <van-cell title="通知对象" use-label-slot>
          <view slot="label" class="flex items-center" v-if="state.parentIds.length !== 4">
            <view class="w-74%">
              <CascaderAddressListMultiplePopup
                :parentLength="state.parentIds.length"
                :beeperId="state.beeperId"
                :buildId="state.buildId"
                :unitId="state.unitIds"
                :floorId="state.floorIds"
                :selectLevel="state.selectLevel"
                @onConfirm="getCascaderData"
                @getLocation="getLocation"
              ></CascaderAddressListMultiplePopup>
              <view class="border-gray h-9 px-2 py-2 box-border flex items-center mt-2" @click="openHouseNumberPopup" v-if="state.cascaderArrLength < 2 && state.parentIds.length < 4">
                <view class="w-95%">
                  <van-tag plain type="primary" v-for="(item, index) in state.houseNumberSelectOptions" :key="index" class="mr-3">
                    {{ item.name }}
                  </van-tag>
                </view>
                <view class="w-5%">
                  <i v-if="state.houseNumberSelectOptions.length > 0" class="i-ix:clear w-4 h-4" @click.stop="clearHouseNumber"></i>
                </view>
              </view>
            </view>
            <view class="w-26% text-align-end">
              <van-button
                @click="
                  () => {
                    paging.reload();
                  }
                "
                custom-style="width:90%;height:164rpx;font-size:60rpx"
                icon="search"
                type="primary"
              />
            </view>
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <!-- 用户列表 -->
    <view class="c-pd">
      <view class="flex items-center bg-white mb-3 c-br c-pd" v-for="(item, index) in state.userList" :key="index">
        <view class="w-20%">
          <image :src="item.imageUrl" class="w-14 h-14" style="border-radius: 50%"></image>
        </view>
        <view class="w-80% pl-2 box-border">
          <view class="mb-2">{{ item.nickName }}</view>
          <view>{{ Tools.ProtectingPhoneNumbers(item.phone) }}</view>
        </view>
      </view>
    </view>
    <template #bottom>
      <view class="c-pd mb-2">
        <van-button type="primary" block @click="submitChange">发送通知</van-button>
      </view>
    </template>
    <van-popup :show="state.notifyShow" custom-style="height: auto;width:80%;border-radius:16rpx" :close-on-click-overlay="false">
      <view class="bg-white w-full h-full">
        <view class="c-pd text-align-center">选择通知类型</view>
        <view>
          <van-grid column-num="3">
            <van-grid-item
              use-slot
              v-for="(item, index) in state.typeArr"
              :key="index"
              @click="
                () => {
                  state.selectType = item;
                  if (item.id === 'activity') {
                    state.notifyPmc = false;
                    state.notifyWay = false;
                  }
                  state.notifyShow = false;
                }
              "
            >
              <view class="text-align-center">
                <image :src="item.imgUrl" :class="item.id === 'sos' ? ['w-10 h-7'] : ['w-9 h-7']"></image>
              </view>
              <view class="mt-1 text-align-center">
                <text>{{ item.name }} </text>
              </view>
              <i v-if="state.selectType?.id === item.id" class="i-ic:sharp-check position-absolute c-color font-bold w-6 h-6 top-0 right-0"></i>
            </van-grid-item>
          </van-grid>
        </view>
      </view>
    </van-popup>
    <van-popup position="bottom" :show="state.popupShow" @close="state.popupShow = false">
      <van-picker show-toolbar value-key="name" :columns="state.houseNumberList" @confirm="handleHouseNumberConfirm" @cancel="state.popupShow = false" title="选择门牌号" />
    </van-popup>
    <VoiceInput :voiceShow="state.voicePopupShow" @onClose="voiceClose" @onConfirm="voiceConfirm" />
  </z-paging>
</template>

<script setup lang="ts">
import useAppStore from '@/store/modules/app';
import CascaderAddressListMultiplePopup from './component/CascaderAddressListMultiplePopup.vue';
import HomeRequest from '@/request/homeRequest';
import userRequest from '@/request/userRequest';
import useToast from '@/hooks/useToast';
import Tools from '@/utils/tools';
import VoiceInput from './component/VoiceInput.vue';

interface IType {
  id: string;
  name: string;
  imgUrl: string;
  flag: boolean;
}

interface IState {
  beeperId: number;
  unitIds: string;
  floorIds: string;
  houseNumber: string;
  btnId: number;
  buildId: string;
  typeArr: IType[];
  selectType?: IType;
  notifyShow: boolean;
  content: string;
  notifyPmc: boolean;
  notifyWay: boolean;
  remark: string;
  address: string;
  cascaderArrLength: number;
  cascaderOptions: IBuildingTreeResNew[];
  userList: IBuildUserList[];
  houseNumberList: IBuildingTreeRes[];
  popupShow: boolean;
  houseNumberSelectOptions: IBuildingTreeRes[];
  parentIds: string[];
  addressType: number;
  selectLevel: number;
  voicePopupShow: boolean;
  currentLocation: string;
}

const store = useAppStore();

const { showToast } = useToast();

const state = reactive<IState>({
  beeperId: store.$state.beeperId,
  unitIds: '',
  floorIds: '',
  buildId: '',
  houseNumber: '',
  btnId: 0,
  typeArr: [
    {
      id: 'fire',
      name: '火警',
      imgUrl: 'http://pic.kanglailab.com/common/fire-alarm.png',
      flag: false,
    },
    {
      id: 'gasLeak',
      name: '燃气泄露',
      imgUrl: 'http://pic.kanglailab.com/common/gas-alarm.png',
      flag: false,
    },
    {
      id: 'lockOpen',
      name: '被盗风险',
      imgUrl: 'http://pic.kanglailab.com/common/opendoor-alarm.png',
      flag: false,
    },
    {
      id: 'sos',
      name: '紧急求助',
      imgUrl: 'https://pic.kanglailab.com/common/sos-alarm.png',
      flag: false,
    },
    {
      id: 'fall',
      name: '洪涝灾害',
      imgUrl: 'https://pic.kanglailab.com/common/flood.png',
      flag: false,
    },
    {
      id: 'liftFault',
      name: '电梯故障',
      imgUrl: 'https://pic.kanglailab.com/common/equip/lift_fault.png',
      flag: false,
    },
    {
      id: 'waterOff',
      name: '停水',
      imgUrl: 'https://pic.kanglailab.com/common/equip/water_off.png',
      flag: false,
    },
    {
      id: 'blackOut',
      name: '停电',
      imgUrl: 'https://pic.kanglailab.com/common/equip/black_out.png',
      flag: false,
    },
    {
      id: 'other',
      name: '其他',
      imgUrl: 'https://pic.kanglailab.com/common/equip/other.png',
      flag: false,
    },
    {
      id: 'activity',
      name: '活动',
      imgUrl: 'https://pic.kanglailab.com/common/equip/activity.png',
      flag: false,
    },
  ],
  notifyShow: true,
  content: '',
  notifyPmc: false,
  notifyWay: false,
  remark: '',
  address: '',
  cascaderArrLength: 0,
  cascaderOptions: [],
  userList: [],
  houseNumberList: [],
  popupShow: false,
  houseNumberSelectOptions: [],
  parentIds: [],
  addressType: 0,
  selectLevel: 0,
  voicePopupShow: false,
  currentLocation: '',
});

const paging = ref();

onLoad((options) => {
  if (!options) return;
  const { btnId, linkUrl } = options;
  const parentIds = linkUrl.split(',');
  state.btnId = btnId;
  state.parentIds = parentIds;
  state.buildId = parentIds[0] || '';
  state.unitIds = parentIds[1] || '';
  state.floorIds = parentIds[2] || '';
  state.houseNumber = parentIds[3] || '';
  const addressMapping: any = {
    0: { addressType: 1, selectLevel: 3 },
    1: { addressType: 2, selectLevel: 3 },
    2: { addressType: 3, selectLevel: 3 },
  };
  const mapping = addressMapping[parentIds.length];
  if (mapping) {
    state.addressType = mapping.addressType;
    state.selectLevel = mapping.selectLevel;
  } else if (parentIds.length === 3) {
    fetchFloorTreeInformation({ parentId: state.floorIds });
  }
});

// 发送通知
const submitChange = () => {
  let params: any = {
    hasLoading: true,
    noticeType: state.selectType?.id,
    remark: state.remark,
    strBuildIds: state.buildId,
    strFloorIds: state.floorIds,
    strUnitIds: state.unitIds,
    houseNumber: state.houseNumber,
    beeperId: state.beeperId,
    btnId: state.btnId,
    notifyPmc: state.notifyPmc === true ? 1 : 0,
    notifyWay: state.notifyWay === false ? '1' : '1,2',
  };
  if (state.selectType?.id === 'activity') params.content = state.content;
  HomeRequest.SendInform(params).then((res) => {
    if (res.status === 0) {
      showToast('操作成功', 'success');
    }
  });
};

//获取组件传递的数据
const getCascaderData = (data: { cascaderArrLength: number; selectedOptions: IBuildingTreeResNew[] }) => {
  state.cascaderArrLength = data.cascaderArrLength;
  if (data.selectedOptions.length !== 0) {
    for (let item of data.selectedOptions) {
      if (Array.isArray(item)) {
        state.floorIds = item.map((item: IBuildingTreeRes) => item.id).join(',');
        if (item.length === 1) {
          fetchFloorTreeInformation({ parentId: state.floorIds });
        }
      } else {
        if (item.levels === 1) {
          state.buildId = String(item.id);
        } else if (item.levels === 2) {
          state.unitIds = String(item.id);
        }
      }
    }
  } else {
    switch (state.parentIds.length) {
      case 0:
        state.buildId = '';
        state.unitIds = '';
        state.floorIds = '';
        break;
      case 1:
        state.unitIds = '';
        state.floorIds = '';
        break;
      case 2:
        state.floorIds = '';
        break;
    }
    state.houseNumberList = [];
    clearHouseNumber();
  }
};

//获取通知用户列表
const getNotifyUserList = (pageNo: number, pageSize: number) => {
  HomeRequest.GetCurrentBuildUser({
    hasLoading: true,
    pageNo,
    pageSize,
    buildIds: state.buildId,
    unitIds: state.unitIds,
    floorIds: state.floorIds,
    beeperId: state.beeperId,
    houseNumber: state.parentIds.length === 4 ? '' : state.houseNumber,
  })
    .then((res) => {
      paging.value.complete(res.data.list);
    })
    .catch((err) => {
      paging.value.complete(false);
    });
};

// 获得门牌号信息
const fetchFloorTreeInformation = (params: { parentId?: string; villageId?: number }) => {
  userRequest.BuildingTree(params).then((res) => {
    state.houseNumberList = Tools.deEmptyChildrenCascader(res.data);
  });
};

const openHouseNumberPopup = () => {
  if (state.houseNumberList.length === 0) {
    showToast('暂无门牌号');
    return false;
  }
  state.popupShow = true;
};

//清空门牌号
const clearHouseNumber = () => {
  state.houseNumber = '';
  state.houseNumberSelectOptions = [];
};

//选择门牌号
const handleHouseNumberConfirm = (e: any) => {
  state.houseNumberSelectOptions = [e.detail.value];
  state.houseNumber = e.detail.value.name;
  state.popupShow = false;
};

const isShowVerify = () => {
  if (state.selectType?.id !== 'activity') {
    return true;
  } else {
    return false;
  }
};

//录音弹窗关闭
const voiceClose = () => {
  state.voicePopupShow = false;
};

//录音结束回调
const voiceConfirm = (e: { text: string; show: boolean }) => {
  state.voicePopupShow = false;
  state.address = state.address + e.text;
};

const getLocation = (e: { location: string }) => {
  state.currentLocation = e.location;
};
</script>

<style lang="scss" scoped>
:deep(.van-grid-item__content) {
  position: relative;
}

.border-gray {
  border: 1px solid #ddd;
  border-radius: 16rpx;
}
</style>
